package com.xunqi.msmservice.controller;

import com.xunqi.commonutils.R;
import com.xunqi.msmservice.service.MsmService;
import com.xunqi.msmservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Created: with IntelliJ IDEA.
 * @author: 夏沫止水
 * @createTime: 2020-08-08 08:55
 **/

@Api(value = "阿里云短信验证服务",tags = "阿里云短信验证服务")
@RestController
@RequestMapping(value = "/edumsm/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final static String GULI_MSM = "guli_msm:";

    /**
     * 发送短信的方法
     * @param phone
     * @return
     */
    @ApiOperation(value = "发送短信验证码",notes = "发送短信验证码",httpMethod = "GET")
    @GetMapping(value = "/send/{phone}")
    public R sendMsm(@ApiParam(name = "phone",value = "手机号",required = true)
                     @PathVariable String phone) {

        //1、从Redis获取验证码，如果获取到直接返回
        String redisCode = stringRedisTemplate.opsForValue().get(GULI_MSM + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            //接口防刷功能
            long currentTime = Long.parseLong(redisCode.split("_")[1]);
            long dateTime = System.currentTimeMillis();
            if (dateTime - currentTime < 60000) {
                //60s内不能再发
                return R.error().message("验证码获取频率太高，请稍后再试");
            }

            return R.ok();
        }

        //2、如果Redis获取不到，进行阿里云发送
        //生成验证码，使用阿里云进行发送
        String code = RandomUtil.getFourBitRandom();

        Map<String,Object> param = new HashMap<>();
        param.put("code",code);

        //调用service发送短信的方法
        boolean isSend = msmService.sendMsm(param,phone);

        if (isSend) {
            //发送成功，把发送成功的验证码发到Redis中进行存储
            //设置有效时间
            String redisStorage = code + "_" + System.currentTimeMillis();
            stringRedisTemplate.opsForValue().set(GULI_MSM + phone,redisStorage,5L, TimeUnit.MINUTES);

            return R.ok();
        }
        return R.error().message("短信发送失败");
    }

}
